package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;

    // synchronized; lock; synchronized(代码块);
    @Override
    public void lock() {

        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111");

        if (lock) {
            // 上锁了
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            if (!StringUtils.isEmpty(num)) {
                num++;
                redisTemplate.opsForValue().set("num", num);
            }

            // 业务逻辑结束，解锁
            redisTemplate.delete("lock");
        } else {
            try {
                Thread.sleep(1000);
                lock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
